package com.vr.core.system.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vr.core.system.system.dao.CommonDaoMapper;
import com.vr.core.system.system.entity.GenericEntity;
import com.vr.core.system.system.service.CommonService;
import com.vr.tool.util.BaseQuery;
import com.vr.tool.util.SelectConditionUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author kenson
 * @Date 2024/12/22 23:32
 */

@Service
public class CommonServiceImpl implements CommonService {
    @Resource
    private CommonDaoMapper commonDaoMapper;

    @Override
    public Page<Map<String, Object>> commonPageList(BaseQuery<Map> query) {
        QueryWrapper<String> queryWrapper = SelectConditionUtil.parseWhereSql(query.getConditions());
        Page<Map<String, Object>> pageList = commonDaoMapper.commonPageList(query.getTableName(), query.getPage(), queryWrapper);
        return pageList;
    }

    @Override
    public boolean commonSave(GenericEntity genericEntity) {
        String tableName = genericEntity.getTableName();
        Map<String, Object> objectMap = genericEntity.getFields();
        objectMap.put("id", IdUtil.simpleUUID());
        String fields = objectMap.keySet().stream().collect(Collectors.joining(","));
        String values = objectMap.values().stream().map(x->{
           if(x == null){
               return null;
           }else{
               return  "'"+String.valueOf(x)+"'";
           }
        }).collect(Collectors.joining(","));
        int i = commonDaoMapper.commonSave(tableName,fields,values);
        return i == 1?true:false;
    }

    @Override
    public boolean commonUpdate(GenericEntity genericEntity) {
        String tableName = genericEntity.getTableName();
        Map<String, Object> objectMap = genericEntity.getFields();
        String id = (String)objectMap.get("id");
        objectMap.remove("id");
        List<String> changeList = new ArrayList<>();
        objectMap.entrySet().forEach( x->{
            if(x.getValue() == null){
                changeList.add(x.getKey()+"= null");
            }else{
                changeList.add(x.getKey()+"='"+x.getValue()+"'");
            }});
        String setSql = String.join(",",changeList);
        commonDaoMapper.commonUpdate(tableName,setSql,id);


        return false;
    }

    @Override
    public boolean commonDelete(GenericEntity genericEntity) {
        int i = commonDaoMapper.commonDelete(genericEntity.getTableName(), genericEntity.getId());
        return i ==1?true:false;
    }
}
